import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import {
  getCartList,
  removeCartItem,
  addCart,
  putCartItem,
  selAllItem
} from '@/api/cart.js'

export const useCartStore = defineStore('cartList', () => {
  const cartList = ref([])
  const setcartList = async () => {
    const res = await getCartList()
    cartList.value = res.result
  }
  const removeCartList = async (ids) => {
    await removeCartItem(ids)
    setcartList()
  }
  const addCartItem = async (obj) => {
    await addCart(obj)
    setcartList()
  }
  const priceTotal = computed(() =>
    cartList.value.length
      ? cartList.value.reduce(
          (total, cur) => total + parseFloat(cur.price) * cur.count,
          0
        )
      : 0
  )
  const numTotal = computed(() =>
    cartList.value.length
      ? cartList.value.reduce((total, cur) => total + cur.count, 0)
      : 0
  )

  const togCartItem = async (id, { selected, count }) => {
    await putCartItem(id, { selected, count })
    setcartList()
  }

  const selectAllItem = async (selected, ids) => {
    await selAllItem(selected, ids)
    setcartList()
  }
  return {
    cartList,
    setcartList,
    removeCartList,
    priceTotal,
    numTotal,
    addCartItem,
    togCartItem,
    selectAllItem
  }
})
